$.zhh.events.on("/employee/permission/resource/", function(space, initial, extras) {

	var RES = { ids:{}, keys:{}, children:{}, parent:{} };

	var v = { };

	// 将操作显示在菜单的同一行, 而不是子节点
	v.onResourceLoadFilter = function(data) {
		var list = $.fn.tree.parser.call(this, data);
		eachResource(list, function(self, parent) {
			RES.ids[this.id] = self;
			RES.keys[this.key] = self;
			RES.children[this.id] = self.children;
			RES.parent[this.id] = parent;
		});
		childrenToAttrs(list, "operates", "type", "MENU");
		return list;
	};
	// fn return false = break; return true = skip children;
	var eachResource = function(list, parent, fn) {
		if ($.isFunction(parent)) { fn = parent; parent = undefined; }
		$.each(list || [], function() {
			var result = fn && fn.call(this, this, parent);
			var result = fn && fn.call(this, this, parent);
			if (result === false) {
				return false;
			}
			if (result !== true && this.children) {
				eachResource(this.children, this, fn);
			}
		});
	};
	// 将符合条件的节点的children转换为一个属性
	var childrenToAttrs = function(list, attr, field, value) {
		eachResource(list, function() {
			if (this.children && this[field] == value) {
				this[attr] = this.children;
				delete this.children;
			}
		});
	};

	v.cascadeClose = function(e) {
		e.popup.xcall("options").xref.launcher.xcall("options").xref.popup.xcall("close");
	};
	v.operateDataFinder = function(e, options) {
		return { selected:RES.ids[options.dataId] };
	};

	// 格式化字段
	v.format = {
		nameToLink: function(value, data) {
			var cls = data["$state$"] == "NORMAL" ? "click-open-xpopup" : "click-open-xpopup color-weak";
			return '<a class="' + cls + '" data-options="xpopup:\'update-{type}\'">' + value + '</a>';
		},
		operatesToLink: function(value, data) {
			if (data.operates) {
				var list = [];
				$.each(data.operates, function() {
					var cls = this["$state$"] == "NORMAL" ? "click-open-xpopup" : "click-open-xpopup color-weak";
					list.push('<a class="' + cls + '" data-options="dataId:\'' + this.id + '\',xpopup:\'update-{type}\',dataFinder:operateDataFinder">' + this.name + '</a>');
				});
				return list.join(" / ");
			}
		}
	};
	
	var findParent = function(selfId, parentType) {
		var parent = RES.parent[selfId];
		while (parent != null && parent.type != parentType) {
			parent = RES.parent[parent.id];
		}
		return parent;
	};
	v.onAfterFillData = {
		create: function(e) { // 打开所有创建对话框之后fillData
			var type = e.form.find("input[name=type]").val();
			if (!e.selected) { return; }
			var parentId;
			if (type == "GROUP" && e.selected.type == "MODULE") {
				parentId = e.selected.id;
			} else if (type == "GROUP" && e.selected.type == "GROUP") {
				// 查找当前GROUP所属的MODULE
				var parent = findParent(e.selected.id, "MODULE");
				if (parent) { parentId = parent.id; }
			} else if (type == "GROUP" && e.selected.type == "MENU") {
				// 查找当前MENU所属的MODULE
				var parent = findParent(e.selected.id, "MODULE");
				if (parent) { parentId = parent.id; }
			} else if (type == "MENU" && e.selected.type == "GROUP") {
				parentId = e.selected.id;
			} else if (type == "MENU" && e.selected.type == "MENU") {
				// 查找当前MENU所属的GROUP
				var parent = findParent(e.selected.id, "GROUP");
				if (parent) { parentId = parent.id; }
			} else if (type == "OPERATE" && e.selected.type == "MENU") {
				parentId = e.selected.id;
			}
			parentId && e.form.find("input[textboxname=parentId]").xcall("setValue", parentId);
		}
	};

	v.onParentIdChange = function(nid, oid) {
		var opts = $(this).xcall("options");
		var ndata = RES.ids[nid];
		var odata = RES.ids[oid];
		var $key = $(this).closest("form").find("input[textboxname=key]");
		if ($key.length) { // 自动填充KEY=上级加冒号
			var nkey;
			var okey = $key.xcall("getValue");
			if (okey) {
				if (odata && okey.startsWith(odata.key)) {
					nkey = ndata.key + ":" + okey.substring(odata.key.length + 1);
				}
			} else {
				nkey = ndata.key + ":";
			}
			nkey && $key.xcall("setValue", nkey);
		}
	};

	var OPERATE_NAME = {
		query: "查询",
		create: ["创建", "新建", "新增"],
		update: "修改",
		delete: "删除",
		import: "导入",
		export: "导出",
		submit: "提交",
		disable: ["锁定", "禁用"],
		enable: ["解锁", "启用"],
		approve: ["审批", "审核"],
		agree: ["同意", "通过"],
		reject: ["拒绝", "驳回"],
		print: "打印"
	};
	var inArray = function(item, array) {
		if (!$.isArray(array)) { array = [array]; }
		return $.inArray(item, array) >= 0;
	};
	v.onOperateNameChange = function(ntext, otext) {
		var opts = $(this).xcall("options");
		var $key = $(this).closest("form").find("input[textboxname=key]");
		if ($key.length == 0) { return; }
		var nsuffix, osuffix;
		for (var k in OPERATE_NAME) {
			if (inArray(ntext, OPERATE_NAME[k])) { nsuffix = k; }
			if (inArray(otext, OPERATE_NAME[k])) { osuffix = k; }
		}
		var nkey;
		var okey = $key.xcall("getValue");
		if (okey) {
			if (okey.endsWith(":")) {
				nkey = okey + (nsuffix || "");
			} else if (okey.endsWith(":" + osuffix)) {
				nkey = okey.substring(0, okey.length - osuffix.length) + (nsuffix || "");
			}
		}
		nkey && $key.xcall("setValue", nkey);
	};


	var onCreateContinue = function(e) {
		var form = e.form;
		var data = e.data;
		form.form("clear").form("disableValidation");
		form.find("input[comboname=type]").combobox("setValue", data.type);
		form.find("input[comboname=parentId]").combotree("setValue", data.parentId);
	};

	space.xui(v);


	$.extend($.fn.validatebox.defaults.rules, {
		// parentType:['模块或菜单组','GROUP|MODULE']
		parentType : {
			validator : function(value, params) {
				var regexp = new RegExp("^(" + params[1] + ")$");
				var value = $(this).closest(".textbox").prev(".textbox-f").xcall("getValue");
				if (!value) { return true; }
				var node = RES.ids[value];
				return node && regexp.test(node.type);
			},
			message : "请选择{0}"
		},
		resLinkFormat : { // 链接地址格式
			validator : function(value) {
				if (/^https?\:\/\/.*/i.test(value)) { return true; }
				return /^(\/.+\/)$/i.test(value);
			},
			message : "必须以/开头且以/结尾"
		},
		resKeyFormat : { // 资源编号格式
			validator : function(value) {
				return /^[_\-\:a-z0-9]*$/i.test(value);
			},
			message : "只支持英文数字横杠和冒号"
		},
		resKeySuffix : { // 不能以冒号开头或结尾
			validator : function(value) {
				return !/(^\:|\:$)/i.test(value);
			},
			message : "请补充完整"
		}
	});
});
